
from fastapi import APIRouter, HTTPException, Depends

from backend.schemas.user import (
    UserCreate, UserOut, UserUpdate, UserPasswordChange, UserList, PaginationParams,
    RoleCreate, RoleUpdate, RoleOut, RoleList, 
    PermissionCreate, PermissionOut, PermissionList
)
from backend.services.user_service import UserService, RoleService, PermissionService
from backend.common.jwt import get_current_active_user, get_current_admin_user, require_permissions
from backend.schemas.response import ResponseBase
from backend.models.user import User
from typing import List, Optional
from fastapi import File, UploadFile
import os
import uuid
import shutil
import hashlib
import base64


router = APIRouter()

# Role endpoints
@router.get("/roles", response_model=ResponseBase[RoleList], summary="获取角色列表")
async def get_roles(
    pagination: PaginationParams = Depends(),
    current_user: User = Depends(require_permissions(["role:list"]))
):
    roles, total = await RoleService.get_roles(page=pagination.page, limit=pagination.limit)
    role_list = []
    
    for role in roles:
        # Transform permissions to permission DTOs
        permissions = []
        for permission in role.permissions:
            permissions.append(PermissionOut(
                id=permission.id,
                name=permission.name,
                code=permission.code,
                description=permission.description,
                created_at=str(permission.created_at),
                updated_at=str(permission.updated_at)
            ))
        
        role_list.append(RoleOut(
            id=role.id,
            name=role.name,
            code=role.code,
            description=role.description,
            permissions=permissions,
            created_at=str(role.created_at),
            updated_at=str(role.updated_at)
        ))
    
    return ResponseBase[RoleList](data=RoleList(items=role_list, total=total))

@router.post("/roles", response_model=ResponseBase[RoleOut], summary="创建角色")
async def create_role(
    role: RoleCreate,
    current_user: User = Depends(require_permissions(["role:create"]))
):
    role_obj = await RoleService.create_role(
        name=role.name,
        code=role.code,
        description=role.description,
        permission_ids=role.permission_ids
    )
    
    # Get fresh role with permissions
    role_obj = await RoleService.get_role_by_id(role_obj.id)
    
    # Transform permissions to permission DTOs
    permissions = []
    for permission in role_obj.permissions:
        permissions.append(PermissionOut(
            id=permission.id,
            name=permission.name,
            code=permission.code,
            description=permission.description,
            created_at=str(permission.created_at),
            updated_at=str(permission.updated_at)
        ))
    
    return ResponseBase[RoleOut](data=RoleOut(
        id=role_obj.id,
        name=role_obj.name,
        code=role_obj.code,
        description=role_obj.description,
        permissions=permissions,
        created_at=str(role_obj.created_at),
        updated_at=str(role_obj.updated_at)
    ))

@router.put("/roles/{role_id}", response_model=ResponseBase[RoleOut], summary="更新角色")
async def update_role(
    role_id: int,
    role: RoleUpdate,
    current_user: User = Depends(require_permissions(["role:update"]))
):
    role_obj = await RoleService.update_role(role_id, role.dict(exclude_unset=True))
    if not role_obj:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    # Transform permissions to permission DTOs
    permissions = []
    for permission in role_obj.permissions:
        permissions.append(PermissionOut(
            id=permission.id,
            name=permission.name,
            code=permission.code,
            description=permission.description,
            created_at=str(permission.created_at),
            updated_at=str(permission.updated_at)
        ))
    
    return ResponseBase[RoleOut](data=RoleOut(
        id=role_obj.id,
        name=role_obj.name,
        code=role_obj.code,
        description=role_obj.description,
        permissions=permissions,
        created_at=str(role_obj.created_at),
        updated_at=str(role_obj.updated_at)
    ))

@router.delete("/roles/{role_id}", response_model=ResponseBase, summary="删除角色")
async def delete_role(
    role_id: int,
    current_user: User = Depends(require_permissions(["role:delete"]))
):
    success = await RoleService.delete_role(role_id)
    if not success:
        raise HTTPException(status_code=404, detail="角色不存在")
    return ResponseBase(message="删除成功")

# Permission endpoints
@router.get("/permissions", response_model=ResponseBase[PermissionList], summary="获取权限列表")
async def get_permissions(
    pagination: PaginationParams = Depends(),
    current_user: User = Depends(require_permissions(["permission:list"]))
):
    permissions, total = await PermissionService.get_permissions(page=pagination.page, limit=pagination.limit)
    permission_list = []
    
    for permission in permissions:
        permission_list.append(PermissionOut(
            id=permission.id,
            name=permission.name,
            code=permission.code,
            description=permission.description,
            created_at=str(permission.created_at),
            updated_at=str(permission.updated_at)
        ))
    
    return ResponseBase[PermissionList](data=PermissionList(items=permission_list, total=total))

@router.post("/permissions", response_model=ResponseBase[PermissionOut], summary="创建权限")
async def create_permission(
    permission: PermissionCreate,
    current_user: User = Depends(require_permissions(["permission:create"]))
):
    permission_obj = await PermissionService.create_permission(
        name=permission.name,
        code=permission.code,
        description=permission.description
    )
    
    return ResponseBase[PermissionOut](data=PermissionOut(
        id=permission_obj.id,
        name=permission_obj.name,
        code=permission_obj.code,
        description=permission_obj.description,
        created_at=str(permission_obj.created_at),
        updated_at=str(permission_obj.updated_at)
    ))

@router.put("/permissions/{permission_id}", response_model=ResponseBase[PermissionOut], summary="更新权限")
async def update_permission(
    permission_id: int,
    permission: PermissionCreate,
    current_user: User = Depends(require_permissions(["permission:update"]))
):
    permission_obj = await PermissionService.update_permission(
        permission_id,
        permission.dict(exclude_unset=True)
    )
    if not permission_obj:
        raise HTTPException(status_code=404, detail="权限不存在")
    
    return ResponseBase[PermissionOut](data=PermissionOut(
        id=permission_obj.id,
        name=permission_obj.name,
        code=permission_obj.code,
        description=permission_obj.description,
        created_at=str(permission_obj.created_at),
        updated_at=str(permission_obj.updated_at)
    ))

@router.delete("/permissions/{permission_id}", response_model=ResponseBase, summary="删除权限")
async def delete_permission(
    permission_id: int,
    current_user: User = Depends(require_permissions(["permission:delete"]))
):
    success = await PermissionService.delete_permission(permission_id)
    if not success:
        raise HTTPException(status_code=404, detail="权限不存在")
    return ResponseBase(message="删除成功")

